package edu.office.applicationRepository;

import edu.office.entities.*;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.inject.Named;

import java.time.LocalDate;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

@Named("reexaminationRepositoryA")
@ApplicationScoped
public class ReexaminationRepository extends ApplicationCommonRepository<Reexamination> {
    @Inject
    StatusofresourcesRepository statusofresourcesRepository;
    @Inject
    TeacherAdminRepository teacherAdminRepository;
    @Inject
   ReexaminationRepository reexaminationRepository;

    public List<Reexamination> getReexaminationId2Examin(Integer userId, boolean isTeacher,Statusofresources status) {
        return find("select * from Reexamination where "+(isTeacher?"toteacher":"STUDENTID")+"=" + userId
                + (status==null?"":" and status=" + status.getID())
        ).list();

    }

    public boolean isKnowledgeInStatus(Knowledge knowledge, int status) {
        return isQuestionOrKnowledgeInStatus(null, knowledge, status);
    }

    public boolean isQuestionInStatus(Question question, int status) {
        return isQuestionOrKnowledgeInStatus(question, null, status);
    }

    private boolean isQuestionOrKnowledgeInStatus(Question question, Knowledge knowledge, int status) {
        Statusofresources statusofresources = getStatus(question, knowledge);
        if (null != statusofresources) {
            return statusofresources.getID().equals(status);
        }
        return false;
    }

    public Statusofresources getStatus(Question question, Knowledge knowledge) {
        Reexamination reexamination;
        if (null != knowledge) {
            Set<Reexamination> reexaminations = getReexamination4Knowledge(knowledge);
            if (!reexaminations.isEmpty()) {
                reexamination = (Reexamination) reexaminations.toArray()[0];
                if (null != reexamination) {
                    return statusofresourcesRepository.find("ID", reexamination.getSTATUS()).firstResult();
                }
            }
        }
        if (null != question) {
            reexamination = (Reexamination) getReexamination4Question(question).toArray()[0];
            if (null != reexamination) {
                return statusofresourcesRepository.find("ID", reexamination.getSTATUS()).firstResult();
            }
        }
        return null;
    }


    public Set<Reexamination> getReexamination4Knowledge(Knowledge knowledge) {
        return new HashSet<>(find("select * from Reexamination where knowledgeid=" + knowledge.getID()).list());

    }

    public Set<Reexamination> getReexamination4Question(Question question) {
        return new HashSet<>(find("select * from Reexamination where questionid=" + question.getID()).list());
    }
    public void setUser4(Reexamination reexamination,User user){
        if(user instanceof  TeacherAdmin) {reexamination.setTEACHERID(user.getId());return;}
        if(user instanceof  Student) {reexamination.setSTUDENTID(user.getId());return;}
    }
    public void createReexamination(Knowledge knowledge, Question question, User user) {
        Reexamination reexamination = new Reexamination();
        reexamination.setSTATUS(statusofresourcesRepository.getReexaming().getID());
        reexamination.setCREATED_DATE(LocalDate.now());
        this.setUser4(reexamination,user);
        if (null != knowledge) {
            if (getReexamination4Knowledge(knowledge).isEmpty()) {
                reexamination.setISCREATE(true);//是在更新，而不是在创建新的
            } else {
                reexamination.setISCREATE(false);//是在更新，而不是在创建新的
            }
            reexamination.setKNOWLEDGEID(knowledge.getID());
            reexamination.setTOTEACHER(teacherAdminRepository.getWhom2Examin(user, null, knowledge).getID());
            create(reexamination);
        }
        if (null != question) {
            if (reexaminationRepository.getReexamination4Question(question).isEmpty()) {
                 reexamination.setISCREATE(true);//是在更新，而不是在创建新的
            } else {
                reexamination.setISCREATE(false);//是在更新，而不是在创建新的
            }
            reexamination.setQUESTIONID(question.getID());
            reexamination.setTOTEACHER(teacherAdminRepository.getWhom2Examin(user, question, null).getID());
            create(reexamination);
        }

    }

    public boolean isEditable(Knowledge knowledge, Question question, User user) {
        Reexamination reexamination;
        if (null != question && null != question.getID()) {
            Set<Reexamination> reexaminations = getReexamination4Question(question);
            if (reexaminations.size() > 0) {
                reexamination = ((Reexamination) reexaminations.toArray()[0]);
            } else {
                return true;
            }
            if (user instanceof Student) {
                if (reexamination.getSTUDENTID() != null) {
                    Statusofresources sr = statusofresourcesRepository.find("ID", reexamination.getSTATUS()).firstResult();
                    return reexamination.getSTUDENTID().equals(user.getId())
                            && (sr.isWaitingExamin() || sr.isSaved());//一审还没开始
                } else {
                    return false;
                }
            } else if (user instanceof TeacherAdmin) {
                return true;
                //return reexamination.getStatus().isWaitingExamin();//审核完成;
            } else if (user instanceof Parent) {
                if (reexamination.getPARENTID() != null) {
                    Statusofresources sr = statusofresourcesRepository.find("ID", reexamination.getSTATUS()).firstResult();
                    return reexamination.getPARENTID().equals(user.getId())
                            && (sr.isWaitingExamin() || sr.isSaved());//一审还没开始
                } else {
                    return false;
                }
            }
        } else if (null != knowledge) {
            Set<Reexamination> reexaminations = (Set<Reexamination>) getReexamination4Knowledge(knowledge);
            if (reexaminations.isEmpty()) {
                return true;
            } else {
                reexamination = (Reexamination) reexaminations.toArray()[0];
            }
            if (user instanceof Student) {
                if (reexamination.getSTUDENTID() != null) {
                    Statusofresources sr = statusofresourcesRepository.find("ID", reexamination.getSTATUS()).firstResult();
                    return reexamination.getSTUDENTID().equals(user.getId())
                            && (sr.isWaitingExamin() || sr.isSaved());//一审还没开始
                } else {
                    return false;
                }
            }
            if (user instanceof TeacherAdmin)
                return true;
            //return !reexamination.getStatus().isWaitingExamin();//审核完成;
            if (user instanceof Parent)
                if (reexamination.getPARENTID() != null) {
                    Statusofresources sr = statusofresourcesRepository.find("ID", reexamination.getSTATUS()).firstResult();
                    return reexamination.getPARENTID().equals(user.getId())
                            && (sr.isWaitingExamin() || sr.isSaved());//一审还没开始
                } else {
                    return false;
                }

        }
        return false;
    }

    private boolean isDeletableThen(Knowledge knowledge, Question question, User user) {//是owner
        if (null != user) {
            if (null != question) {
                Set<Reexamination> setReexaminations = getReexamination4Question(question);
                if (setReexaminations.isEmpty()) {
                    return false;
                } else {
                    Reexamination reexamination = (Reexamination) setReexaminations.toArray()[0];
                    if (user instanceof Student)
                        if (reexamination.getSTUDENTID() != null) {
                            Statusofresources sr = statusofresourcesRepository.find("ID", reexamination.getSTATUS()).firstResult();
                            return reexamination.getSTUDENTID().equals(user.getId())
                                    && (sr.isExaminFailed() || sr.isSaved());//审核未通过才可能删除
                        } else {
                            return false;
                        }
                    if (user instanceof TeacherAdmin)
                        if (reexamination.getTEACHERID() != null) {
                            Statusofresources sr = statusofresourcesRepository.find("ID", reexamination.getSTATUS()).firstResult();
                            return reexamination.getTEACHERID().equals(user.getId())
                                    && (sr.isExaminFailed() || sr.isSaved());
                        } else {
                            return false;
                        }
                    if (user instanceof Parent)
                        if (reexamination.getPARENTID() != null) {
                            Statusofresources sr = statusofresourcesRepository.find("ID", reexamination.getSTATUS()).firstResult();
                            return reexamination.getPARENTID().equals(user.getId())
                                    && (sr.isExaminFailed() || sr.isSaved());
                        } else {
                            return false;
                        }
                }
            }
        } else if (null != knowledge) {
            Reexamination reexamination;
            Set<Reexamination> reexaminations = getReexamination4Knowledge(knowledge);
            if (reexaminations.isEmpty()) {
                return false;
            } else {
                reexamination = (Reexamination) reexaminations.toArray()[0];
            }
            if (user instanceof Student)
                if (reexamination.getSTUDENTID() != null) {
                    Statusofresources sr = statusofresourcesRepository.find("ID", reexamination.getSTATUS()).firstResult();
                    return reexamination.getSTUDENTID().equals(user.getId())
                            && (sr.isExaminFailed() || sr.isSaved());
                } else {
                    return false;
                }
            if (user instanceof TeacherAdmin)
                if (reexamination.getTEACHERID() != null) {
                    Statusofresources sr = statusofresourcesRepository.find("ID", reexamination.getSTATUS()).firstResult();
                    return reexamination.getTEACHERID().equals(user.getId())
                            && (sr.isExaminFailed() || sr.isSaved());
                } else {
                    return false;
                }
            if (user instanceof Parent)
                if (reexamination.getPARENTID() != null) {
                    Statusofresources sr = statusofresourcesRepository.find("ID", reexamination.getSTATUS()).firstResult();
                    return reexamination.getPARENTID().equals(user.getId())
                            && (sr.isExaminFailed() || sr.isSaved());
                } else {
                    return false;
                }


        }
        return false;
    }

    public boolean isDeletable(Knowledge knowledge, Question question, User user) {
        if (user instanceof TeacherAdmin) {
            return true;
        } else {
            return isDeletableThen(knowledge, question, user);
        }
    }


    private List<Reexamination> getReexaminationListRecorderBy(User user, Integer status, int isQuestion) {
        //type=0表示知识点；type=1表示题目
        String temString = "";
        switch (isQuestion) {
            case 0:
                temString += " knowledgeId is not null";
                break;
            case 1:
                temString += " questionid is not null";
                break;
            default:
                return new LinkedList<>();
        }
        if (user instanceof Student)
            temString += " and studentid=" + ((Student) (user)).getId();
        if (user instanceof Parent)
            temString += " and parentid=" + ((Parent) (user)).getID();
        if (user instanceof TeacherAdmin)
            temString += " and teacherid=" + ((TeacherAdmin) (user)).getID();

        if (null != status) {//第一次审核
            temString += " and  status=" + status;
        }
        return list("select * from Reexamination where " + temString);
    }

    public List<Reexamination> getReexaminationKnowledgeListRecorderBy(User user, Integer status) {
        return getReexaminationListRecorderBy(user, status, 0);
    }

    public List<Reexamination> getReexaminationQuestionListRecorderBy(User user, Integer status) {
        return getReexaminationListRecorderBy(user, status, 1);
    }

    public List<Reexamination> getReexaminationNeedToBeExamined(TeacherAdmin teacherAdmin, int status, int isQuestion, Integer dsecondStatus) {
        //type=0表示知识点；type=1表示题目
        String temString = "";
        switch (isQuestion) {
            case 0:
                temString += " knowledgeId is not null";
                break;
            case 1:
                temString += " questionid is not null";
                break;
            default:
                return new LinkedList<>();
        }
        if (null == dsecondStatus) {//第1次审核
            temString += " and toteacher=" + teacherAdmin.getID();
            temString += " and  status=" + status;
        } else {//第2次审核的条件是第1次审核通过！！
            temString += " and  status=1 and status2nd=" + dsecondStatus;
        }
        return list("select * from Reexamination where " + temString);
    }

    public boolean isMineDue2Reexamin(Knowledge knowledge, Question question, User user, int status, int  secondStatus) {
        if (user instanceof TeacherAdmin)
            if (null != knowledge) {
                Set<Reexamination> reexaminations = getReexamination4Knowledge(knowledge);
                if (!reexaminations.isEmpty()) {
                    return statusEqual(status, (Reexamination) reexaminations.toArray()[0]);
                }
            } else if (null != question) {
                return statusEqual(status, ((Reexamination) getReexamination4Question(question).toArray()[0]));
            } else {
                if (null != knowledge) {
                    Set<Reexamination> reexaminations = getReexamination4Knowledge(knowledge);
                    if (!reexaminations.isEmpty()) {
                        return statusEqual(secondStatus, ((Reexamination) reexaminations.toArray()[0]));
                    }
                } else if (null != question) {
                    return statusEqual(secondStatus, ((Reexamination) getReexamination4Question(question).toArray()[0]));
                }
                return false;
            }
        return false;
    }

    private boolean statusEqual(int status, Reexamination reexamination) {
        return reexamination.getSTATUS() == status;
    }


    private String setPassStatus(boolean passed, User user, Reexamination reexamination) {
        if (!passed) {
            if (user instanceof TeacherAdmin) {
                reexamination.setSTATUS(statusofresourcesRepository.getPassedFaild().getID());
            } else {
                reexamination.setSTATUS2ND(statusofresourcesRepository.getPassedFaild().getID());
                reexamination.setSTATUS(statusofresourcesRepository.getPassedFaild().getID());//二审没通过，则一审也自动没通过
            }
        } else {
            if (user instanceof TeacherAdmin) {
                reexamination.setSTATUS(statusofresourcesRepository.getPassed().getID());
            } else {
                reexamination.setSTATUS2ND(statusofresourcesRepository.getPassed().getID());
                reexamination.setSTATUS(statusofresourcesRepository.getPassedFaild().getID());//二审没通过，则一审也自动没通过
            }
        }
        edit();
        return null;
    }
}
